﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using SABnzbdNET.Commands;
using SABnzbdNET.Events;
using SABnzbdNET.Model;
using SABnzbdNET.ServiceAgents;

namespace SABnzbdNET.ViewModels
{
    public class WarningsViewModel : BaseViewModel
    {
        #region Fields and properties

        private ObservableCollection<string> warnings;
        private string lastUpdated;
        private readonly IEventAggregator eventAggregator;

        public ObservableCollection<string> Warnings
        {
            get {
                if (warnings != null && warnings.Count > 0)
                {
                    var temp = new ObservableCollection<string>();
                    foreach (var warning in warnings.OrderByDescending(w => w))
                    {
                        temp.Add(warning);
                    }
                    return temp;
                }
                return warnings; 
            }
            set
            {
                warnings = value;
                OnPropertyChanged("Warnings");
            }
        }
        public string LastUpdated
        {
            get { return lastUpdated; }
            set
            {
                lastUpdated = value;
                OnPropertyChanged("LastUpdated");
            }
        }

        #endregion

        public WarningsViewModel()
        {
            eventAggregator = EventAggregatorProvider.Instance;
            eventAggregator.Subscribe<UpdateServerWarningsMessage>(message => GetWarnings());
        }

        private void GetWarnings()
        {
            Mouse.OverrideCursor = Cursors.AppStarting;
            SetStatusMessage("Updating", "Updating");
            new ServerAgent().GetWarnings(DeployResult);
        }

        private void DeployResult(WarningList warningsList, string errorMessage)
        {
            if (warningsList != null && warningsList.Warnings != null)
            {
                Warnings = warningsList.Warnings;
                SetStatusMessage("Last updated " + DateTime.Now, string.Empty);
            }
            else
                SetStatusMessage("Error updating warnings: " + errorMessage, string.Empty);
            Mouse.OverrideCursor = null;
        }

        private void SetStatusMessage(string statusMessage, string notifyIconTooltip)
        {
            eventAggregator.Publish(new UpdateStatusInfoMessage
            {
                StatusMessage = statusMessage,
                NotifyIconMessage = notifyIconTooltip
            });
        }
    }
}
